// pages/seal/paymentResult/paymentResult.js
import config from '../../../utils/config';
import PaymentUtil from '../../../utils/payment';

Page({
  data: {
    orderId: '',
    paymentStatus: 'pending', // pending, success, failed
    orderInfo: null,
    loading: true
  },

  onLoad(options) {
    if (options.orderId) {
      this.setData({
        orderId: options.orderId
      });
      this.queryPaymentStatus();
    }
  },

  // 查询支付状态
  async queryPaymentStatus() {
    try {
      const token = wx.getStorageSync('token');
      if (!token) {
        throw new Error('用户未登录');
      }

      const orderStatus = await PaymentUtil.queryOrderStatus(this.data.orderId, token);
      
      this.setData({
        paymentStatus: orderStatus.status,
        orderInfo: orderStatus,
        loading: false
      });

      // 根据支付状态处理
      if (orderStatus.status === 'success') {
        this.handlePaymentSuccess();
      } else if (orderStatus.status === 'failed') {
        this.handlePaymentFailed();
      }

    } catch (error) {
      console.error('查询支付状态失败:', error);
      this.setData({
        paymentStatus: 'failed',
        loading: false
      });
      
      wx.showToast({
        title: '查询支付状态失败',
        icon: 'none'
      });
    }
  },

  // 支付成功处理
  handlePaymentSuccess() {
    PaymentUtil.showPaymentResult(true, '支付成功', () => {
      // 跳转到订单详情页面
      wx.redirectTo({
        url: `/pages/seal/orderDetail/orderDetail?orderId=${this.data.orderId}`
      });
    });
  },

  // 支付失败处理
  handlePaymentFailed() {
    PaymentUtil.showPaymentResult(false, '支付失败', () => {
      // 可以选择重新支付或返回
      wx.showModal({
        title: '提示',
        content: '支付失败，是否重新支付？',
        success: (res) => {
          if (res.confirm) {
            // 返回订单页面重新支付
            wx.navigateBack();
          } else {
            // 返回首页
            wx.switchTab({
              url: '/pages/index/index'
            });
          }
        }
      });
    });
  },

  // 重新支付
  handleRepayment() {
    wx.navigateBack();
  },

  // 查看订单详情
  handleViewOrder() {
    wx.redirectTo({
      url: `/pages/seal/orderDetail/orderDetail?orderId=${this.data.orderId}`
    });
  },

  // 返回首页
  handleGoHome() {
    wx.switchTab({
      url: '/pages/index/index'
    });
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.queryPaymentStatus().finally(() => {
      wx.stopPullDownRefresh();
    });
  }
}); 